<template>
  <el-card class="comment">
    <h2 class="titleHeader">评论管理</h2>
    <CommentHeader
      @whereSearch="whereSearch"
      @deleteAllId="deleteAllId"
    ></CommentHeader>
    <CommentList
      :commentsData="commentsData"
      @deleteId="deleteId"
      ref="commentListFef"
    ></CommentList>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleChangePage"
        :hide-on-single-page="Number(count) < 5"
        :total="Number(count)"
        :page-size="5"
        layout="prev, pager, next"
      />
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, defineAsyncComponent } from 'vue'
import { getComments, deleteComment } from '@/utils/commentHttp'
import { ElMessage } from 'element-plus'
// 导入头部
const CommentHeader = defineAsyncComponent(
  () => import('@/components/comment/CommentHeader.vue')
)

// 导入图书列表
const CommentList = defineAsyncComponent(
  () => import('@/components/comment/CommentList.vue')
)

// 获取列表数据
type commentsData = {
  address?: string
  articleTitle?: string
  content?: string
  createTime?: string
  parentId?: string
  report?: string
  _id?: string
  user?: {
    avatar?: string
    username?: string
  }
}
const commentsData = ref<commentsData[]>([])
let page = 1
let count = ref<number>(0)
// 点击搜索查询
type where = {
  articleTitle?: string
  address?: string
  content?: string
  report?: string
}
let where: where = {}
const getListData = () => {
  getComments(page, where).then((res) => {
    count.value = res.data.data.count
    commentsData.value = res.data.data.data
  })
}
// 先获取一下数据
getListData()
// 分页切换
const handleChangePage = (currentpage: number): void => {
  page = currentpage
  getListData()
}
//
const deleteId = async (ids: string[]) => {
  await deleteComment(ids)
  ElMessage.success('删除')
  getListData()
}

// 删除多选
const commentListFef = ref<InstanceType<typeof CommentList>>()
const deleteAllId = () => {
  if (!commentListFef.value) return
  if (!commentListFef.value.multipleSelection.length)
    return ElMessage.error('不能一个不选')
  deleteId(
    commentListFef.value.multipleSelection.map((item) => item._id) as string[]
  )
}
const whereSearch = (data: where) => {
  where = data
  getListData()
}
</script>

<style lang="scss" scoped>
.comment {
  padding: 0px 20px 40px;

  .pagination {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
